﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.BizTalk.ExplorerOM;
using Microsoft.BizTalk.Operations;

namespace DBLOG.BizTalk.BizTalkExplorerServices.Core
{
    public abstract class BizTalkExplorerBase : IDisposable
    {
        internal BtsCatalogExplorer _explorer;
        internal BizTalkOperations _operations;

        internal BizTalkExplorerBase()
        {
            try
            {
                InitializeApiObjects();
            }
            catch (Exception ex)
            {
                throw new BizTalkManagementException("Could not initialize BizTalk API objects!", ex);
            }
        }

        /// <summary>
        /// Initializes the BizTalk API objects with default settings
        /// The server name will be 'localhost' and the BizTalk database name will be 'BizTalkMgmtDb'
        /// </summary>
        internal void InitializeApiObjects()
        {
            InitializeApiObjects(BizTalkSettings.ServerName, BizTalkSettings.ManagementDatabase);
        }

        /// <summary>
        /// Initializes the BizTalk API objects
        /// </summary>
        /// <param name="BizTalkServer">The BizTalk server name</param>
        /// <param name="BizTalkManagementDatabase">The BizTalk database name</param>
        internal void InitializeApiObjects(string BizTalkServer, string BizTalkManagementDatabase)
        {
            if (String.IsNullOrEmpty(BizTalkServer))
                throw new ArgumentNullException("BizTalkServer");

            if (String.IsNullOrEmpty(BizTalkManagementDatabase))
                throw new ArgumentNullException("BizTalkManagementDatabase");

            this._explorer = new BtsCatalogExplorer();
            this._explorer.ConnectionString = String.Format("Integrated Security=SSPI;database={0};server={1}", BizTalkManagementDatabase, BizTalkServer);

            this._operations = new BizTalkOperations(BizTalkServer, BizTalkManagementDatabase);
        }

        public void Dispose()
        {
            if (this._explorer != null)
                this._explorer.Dispose();
            if (this._operations != null)
                this._operations = null;
        }
    }
}